
//chatClient.c
//Ashish Tomar
//2009/1/27
//Network Security -- HW0




#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <signal.h>



#define MAXDATASIZE 1000


void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) {
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}



int main(int argc, char *argv[])
{
		//declaration
		int sock, portNo;
		char *userName;
		int status;

		
		int sockfd, numbytes;  
		char buf[MAXDATASIZE];
		struct addrinfo hints, *servinfo, *p;
		int rv;
		char s[INET6_ADDRSTRLEN];

		//declaration section end

		//main code
		if(argc!=4)
		{
				printf("This program requires 3 arguments ip adress, port no & username\n");
		}

		userName=argv[3];
		portNo=atoi(argv[2]);

		memset(&hints, 0, sizeof hints); // make sure the struct is empty
		hints.ai_family = AF_UNSPEC;     // don't care IPv4 or IPv6
		hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
		hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

		if ((status = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0)
			{
				printf( "getaddrinfo: %s\n", gai_strerror(status));
				return 1;
			}

		for(p = servinfo; p != NULL; p = p->ai_next) 
			{
				if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
				{
					perror("client: socket");
					continue;
				}

				if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
				{
					close(sockfd);
					perror("client: connect");
					continue;
				}

				break;
			 }

			if (p == NULL)
			{
				fprintf(stderr, "client: failed to connect\n");
				return 2;
			}

		inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
        printf("client: connecting to %s\n", s);

		freeaddrinfo(servinfo); // all done with this structure
		if (send(sockfd, argv[3], strlen(argv[3]), 0) == -1)
		perror("send");


   if(!fork())
	   {
			while(1)
				{
				
						 if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
						{
							perror("recv");
							exit(1);
						 }
						 else
						{
								buf[numbytes] = '\0';
								if(numbytes >2)
								printf("client: received '%s'\n",buf);

						 }
				}
   }
   
   else
	{
			while(1)
			{
					char mes[1000];
					//char * mes;
					gets(mes);

					 if (send(sockfd, mes, strlen(mes), 0) == -1)
					  perror("send");

			 }
	}

    close(sockfd);
		return 0;
}
